package com.mooc.yohoshop.ui.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.ToastUtils;
import com.mooc.yohoshop.entity.BaseEntity;
import com.mooc.yohoshop.widget.LoadingDialog;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public abstract class BaseFragment extends Fragment implements Observer<BaseEntity> {

    protected CompositeDisposable compositeDisposable = new CompositeDisposable();
    private LoadingDialog dialog;
    protected View rootView;

    @Nullable
    @Override
    public View onCreateView(@androidx.annotation.NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(layout(),container,false);
        return rootView;
    }

    protected abstract int layout();

    protected abstract void init();

    protected abstract void initData();

    protected <T extends View>T f(int id){
        return rootView.findViewById(id);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        compositeDisposable.dispose();
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        compositeDisposable.add(d);
        dialog = new LoadingDialog(getActivity());
        dialog.show();
    }

    @Override
    public void onNext(@NonNull BaseEntity baseEntity) {
        if (baseEntity.status.equals("200")) {
            result(baseEntity);
            return;
        }
    }

    @Override
    public void onError(@NonNull Throwable e) {
        ToastUtils.showShort("请求出错");
    }

    @Override
    public void onComplete() {
        dialog.dismiss();
    }

    protected abstract void result(BaseEntity baseEntity);

}
